package com.example.chatapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable()) // 禁用CSRF，因为我们使用的是REST API
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(
                    "/",
                    "/index.html",
                    "/login.html",
                    "/register.html",
                    "/login.js",
                    "/chat.html",
                    "/chat.js",
                    "/auth/login",
                    "/auth/register",
                    "/auth/current",
                    "/auth/logout",
                    "/auth/switchRoom",
                    "/auth/online-users",
                    "/friends/**",
                    "/history/**",
                    "/health/**",
                    "/ws/**"
                ).permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.disable()) // 禁用默认的表单登录
            .httpBasic(basic -> basic.disable()); // 禁用HTTP Basic认证

        return http.build();
    }
}
